import React, { Component } from 'react';
import DatePicker from 'react-native-datepicker';
import {
  View,
  Text,
  StyleSheet,
  Image,
  TouchableOpacity,
  Platform,
  DeviceEventEmitter,
} from 'react-native';

import ImagePicker from 'react-native-image-crop-picker';
import Picker from 'react-native-picker';
import PxToDp from '../../utils/PxToDp';
import FontFamilys from '../../utils/FontFamilys';
import NavCon from '../Public/NavCon';
import { changeAvatar, changeAvatarStore, fetchPerson, fetchPersonSex } from '../../actions/profileActions';
import Modalext from '../Public/ModalExt';
import Base from '../../utils/Base';
import fetchDealerInfo from '../../actions/dealerInfoActions';
import ModifyName from '../../containers/ModifyNameContainer';
import ModifyPersonIntroduce from './ModifyPersonIntroduce';
import fetchModifyName from '../../actions/ModifyPersonActions';

/* global host */
const { width, onePR } = Base.window;
let sex = '';
const sexList = [
  {
    name: '男',
    id: 1,
  },
  {
    name: '女',
    id: 0,
  },
];

export default class EditProfile extends Component {
  constructor(props) {
    super(props);
    this.state = {
      ModelshowPer: false,
      image: null,
      username: this.props.PerformanceData && this.props.PerformanceData.data &&
        this.props.PerformanceData.data.cur_user ? this.props.PerformanceData.data.cur_user.username : '',
      isClick: false,
      ModelshowSex: false,
      sex: this.props.PerformanceData && this.props.PerformanceData.data &&
        this.props.PerformanceData.data.cur_user === 1 ? '男' : '女',
      intros: this.props.PerformanceData && this.props.PerformanceData.data &&
        this.props.PerformanceData.data.cur_user ? this.props.PerformanceData.data.cur_user.intro : '',
      date: this.props.PerformanceData && this.props.PerformanceData.data &&
        this.props.PerformanceData.data.cur_user ? this.props.PerformanceData.data.cur_user.workbeginday : '',
      sexSelect: 0,
      pickerStatus: true,
    };
    const { dispatch } = this.props;
    dispatch(fetchDealerInfo());
  }

  _setModalVisible(visible) {
    this.setState({ ModelshowPer: visible }, () => {
    });
  }
  _setModalVisibleSex(visible) {
    this.setState({ ModelshowSex: visible }, () => {
    });
  }
  _goModifyName() {
    if (this.state.pickerStatus) {
      const { dispatch } = this.props;
      const parentUserName = this.props.userName ? this.props.userName : this.state.username;
      this.props.navigator.push({
        title: 'ModifyName',
        name: 'ModifyName',
        component: ModifyName,
        passProps: { parentUserName, dispatch },
      });
    } else {
      this._hidePicker();
    }
    console.log(`${this.state.pickerStatus}`);
  }
  _goModifyIntroduce() {
    if (this.state.pickerStatus) {
      const { dispatch } = this.props;
      const parentIntro = this.props.perIntro ? this.props.perIntro : this.state.intros;
      const PerformanceData = this.props.PerformanceData;
      this.props.navigator.push({
        title: 'ModifyPersonIntroduce',
        name: 'ModifyPersonIntroduce',
        component: ModifyPersonIntroduce,
        passProps: {
          parentIntro,
          dispatch,
          PerformanceData,
        },
      });
    } else {
      this._hidePicker();
    }
  }
  _sexCommit() {
    this._setModalVisibleSex(false);
    if (sex === '1' || sex === 1) {
      sex = '男';
      this.setState({ sex: '男' });
    } else {
      this.setState({ sex: '女' });
      sex = '女';
    }
    this.props.dispatch(fetchPersonSex(sex));
    const PerformanceData = this.props.PerformanceData;
    let data = {};
    if (PerformanceData && PerformanceData.data) {
      data = PerformanceData.data;
      if (data && data.cur_user) {
        this.props.dispatch(fetchModifyName(data.cur_user.username, sex,
          data.cur_user.intro ? data.cur_user.intro : '', `${data.cur_user.utype}`,
          data.cur_user.uid, data.cur_user.workbeginday, data.cur_user.email, '', ''));
      }
    }
  }
  pickSingleWithCamera(cropping) {
    this.setState({ ModelshowPer: false });
    const { dispatch } = this.props;
    ImagePicker.openCamera({
      cropping,
      width: 500,
      height: 500,
      includeBase64: true,
    }).then((image) => {
      const PerformanceData = this.props.PerformanceData;
      let data = {};
      if (PerformanceData && PerformanceData.data) {
        data = PerformanceData.data;
        dispatch(changeAvatar(`data:image/jpeg;base64,${image.data}`, () => {
          const Icon = `${host}/static/${data.cur_user.avatar}?t=${(new Date()).getTime()}`;
          dispatch(changeAvatarStore(Icon));
        }));
      }
    }).catch(() => {
      DeviceEventEmitter.emit('showToast', '上传图片失败');
    });
  }

  pickSingle(cropit, circular = false) {
    this.setState({ ModelshowPer: false });
    const { dispatch } = this.props;
    ImagePicker.openPicker({
      width: 300,
      height: 300,
      cropping: cropit,
      includeBase64: true,
      cropperCircleOverlay: circular,
      compressImageMaxWidth: 640,
      compressImageMaxHeight: 480,
      compressImageQuality: 0.5,
      compressVideoPreset: 'MediumQuality',
    }).then((image) => {
      // const saler = this.props.saler;
      dispatch(changeAvatar(`data:image/jpeg;base64,${image.data}`, () => {
        const PerformanceData = this.props.PerformanceData;
        let data = {};
        if (PerformanceData && PerformanceData.data) {
          data = PerformanceData.data;
          const Icon = `${host}/static/${data.cur_user.avatar}?t=${(new Date()).getTime()}`;
          dispatch(changeAvatarStore(Icon));
        }
      }));
    }).catch(() => {
      DeviceEventEmitter.emit('showToast', '上传图片失败');
    });
  }

  _getDate() {
    const date = new Date();
    const year = date.getFullYear();
    let month = date.getMonth() + 1;
    let day = date.getDate();
    const hours = date.getHours();
    const minutes = date.getMinutes();
    if (month.toString().length === 1) {
      month = `0${month}`;
    }
    if (day.toString().length === 1) {
      day = `0${day}`;
    }
    return `${year}.${month}.${day} ${hours}:${minutes}`;
  }

  _onDateChange(date) {
    const { dispatch } = this.props;
    const currentDate = this._getDate();
    if (date > currentDate || date === currentDate) {
      DeviceEventEmitter.emit('showToast', '从业时间要小于当前时间，请重新选择！');
      return;
    }
    dispatch(fetchPerson(date));
    this.setState({ date }, () => {
      const PerformanceData = this.props.PerformanceData;
      let data = {};
      if (PerformanceData && PerformanceData.data) {
        data = PerformanceData.data;
        if (data && data.cur_user) {
          this.props.dispatch(fetchModifyName(data.cur_user.username, sex,
          data.cur_user.intro ? data.cur_user.intro : '', `${data.cur_user.utype}`,
          data.cur_user.uid, date, data.cur_user.email, '', ''));
        }
      }
    });
  }

  back() {
    this._hidePicker();
    this.props.navigator.pop();
  }

  _showSexPicker() {
    const sexListNew = [];
    if (sexList && sexList.length > 0) {
      sexList.map((item) => {
        sexListNew.push(item.name);
      });
    }
    this.setState({ pickerStatus: false });
    Picker.init({
      pickerData: sexListNew,
      selectedValue: [this.props.perSex ? this.props.perSex : this.state.sex],
      pickerConfirmBtnText: '确认',
      pickerCancelBtnText: '取消',
      pickerTitleText: '',
      pickerBg: [255, 255, 255],
      pickerConfirmBtnColor: [65, 140, 255, 1],
      pickerCancelBtnColor: [139, 140, 142, 1],
      pickerTitleColor: [18, 18, 18, 1],
      pickerToolBarFontSize: 18,
      pickerFontSize: 15,
      onPickerConfirm: (data) => {
        this.setState({ pickerStatus: true });
        sexList.map((item) => {
          if (item.name === data[0]) {
            sex = item.id;
            this.setState({ sexSelect: item.name });
            this._sexCommit();
          }
        });
      },
      onPickerCancel: (data) => {
        console.log(data);
        this.setState({ pickerStatus: true });
      },
      onPickerSelect: (data) => {
        console.log(data);
      },
    });
    Picker.show();
  }

  _hidePicker() {
    Picker.isPickerShow((status) => {
      this.setState({ pickerStatus: status });
      Picker.hide();
    });
  }

  _avtor() {
    this._hidePicker();
    this._setModalVisible(true);
  }

  _cancleAvator() {
    this._setModalVisible(false);
    this.setState({ pickerStatus: true });
  }

  render() {
    let Icon = '';
    const PerformanceData = this.props.PerformanceData;
    let data = {};
    if (PerformanceData && PerformanceData.data) {
      data = PerformanceData.data;
      if (data && data.cur_user) {
        Icon = this.props.avatorStore ? this.props.avatorStore : `${host}/static/${data.cur_user.avatar}?t=${(new Date()).getTime()}`;
      }
    }
    return (
      <TouchableOpacity
        style={style.container}
        onPress={() => this._hidePicker()}
        disabled={this.state.pickerStatus}
      >
        <NavCon backName="" currentTitle="个人资料" onPress={() => this.back()} />
        <TouchableOpacity
          style={style.wrapper}
          onPress={() => this._hidePicker()}
        >
          <View style={style.body}>


            <View style={[style.infoContainer, style.bg]}>
              <TouchableOpacity
                focusedOpacity={0.8}
                style={style.infoListImg}
                onPress={() => this._avtor()}
              >
                <Text style={style.listLeft}>更换头像</Text>
                <TouchableOpacity
                  style={[style.listRight, style.headImg]}
                >
                  {
                  Icon
                  ?
                    <Image
                      style={style.headPic}
                      source={{ uri: Icon }}
                    />
                  :
                    <Image
                      style={style.headPic}
                      source={require('../../img/nav_head_default.png')}
                    />
                }
                  <Image
                    style={style.next}
                    source={require('../../img/next.png')}
                  />
                </TouchableOpacity>
              </TouchableOpacity>
            </View>
            <View style={[style.infoContainer, style.bg]}>
              <TouchableOpacity
                focusedOpacity={0.8}
                style={style.infoList}
                onPress={() => this._goModifyName()}
              >
                <Text style={style.listLeft}>姓名</Text>
                <View style={style.listRight}>
                  <Text style={style.rightInfo}>
                    {this.props.userName ? this.props.userName : this.state.username}
                  </Text>
                  <Image
                    style={style.next}
                    source={require('../../img/next.png')}
                  />
                </View>
              </TouchableOpacity>
              <TouchableOpacity
                focusedOpacity={0.8}
                style={style.infoList}
                onPress={() => this._showSexPicker()}
              >
                <Text style={style.listLeft}>性别</Text>
                <View style={style.listRight}>
                  <Text style={style.rightInfo}>
                    {this.props.perSex ? this.props.perSex : this.state.sex}
                  </Text>
                  <Image
                    style={style.next}
                    source={require('../../img/next.png')}
                  />
                </View>
              </TouchableOpacity>
              <TouchableOpacity
                focusedOpacity={0.8}
                style={style.infoList}
              >
                <Text style={style.listLeft}>从业时间</Text>
                <View style={style.listRight}>
                  <DatePicker
                    style={style.datepicker}
                    date={this.props.perTime ? this.props.perTime : this.state.date}
                    showIcon={false}
                    mode="date"
                    format="YYYY.MM.DD"
                    confirmBtnText="确认"
                    cancelBtnText="取消"
                    customStyles={{
                      showIcon: false,
                      dateIcon: {
                        left: 0,
                        top: 4,
                        marginLeft: 0,
                      },
                      dateText: {
                        fontFamily: FontFamilys(),
                        color: '#999',
                        fontSize: PxToDp(14),
                      },
                      dateInput: {
                        borderRadius: PxToDp(2),
                        height: PxToDp(28),
                        width: PxToDp(160),
                        borderWidth: 0,
                      },
                    }}
                    onDateChange={date => this._onDateChange(date)}
                  />
                  <Image
                    style={[style.next, style.dateNext]}
                    source={require('../../img/next.png')}
                  />
                </View>
              </TouchableOpacity>
              <TouchableOpacity
                focusedOpacity={0.8}
                style={style.infoList}
                onPress={() => this._goModifyIntroduce()}
              >
                <Text style={style.listLeft}>个人介绍</Text>
                <View style={style.listRight}>
                  <Text
                    style={style.rightInfo}
                    numberOfLines={1}
                  >
                    {this.props.perIntro ? this.props.perIntro : this.state.intros}
                  </Text>
                  <Image
                    style={style.next}
                    source={require('../../img/next.png')}
                  />
                </View>
              </TouchableOpacity>
            </View>
          </View>
        </TouchableOpacity>
        <Modalext onRequestClose={() => this._setModalVisible(false)} animationType={'slide'} transparent visible={this.state.ModelshowPer}>
          <View style={style.modal}>
            <TouchableOpacity
              style={{ width: width - 34, height: 50, alignItems: 'center', borderBottomWidth: 1, borderStyle: 'solid', borderColor: '#f5f5f5' }}
              onPress={() => this.pickSingleWithCamera(true)}
            >
              <Text style={{ marginTop: 15 }}>拍照</Text>
            </TouchableOpacity>
            <TouchableOpacity
              style={{ width: width - 34, height: 50, alignItems: 'center' }}
              onPress={() => this.pickSingle(true, true)}
            >
              <Text style={{ marginTop: 15 }}>从相册中选择</Text>
            </TouchableOpacity>
          </View>
          <View style={{ width: width - 34, height: 50, backgroundColor: '#fff', marginTop: 12, marginBottom: 21, borderRadius: 6, alignItems: 'center' }} >
            <TouchableOpacity
              style={{ width: width - 34, height: 50, alignItems: 'center' }}
              onPress={() => this._cancleAvator()}
            >
              <Text style={{ marginTop: 15 }}>取消</Text>
            </TouchableOpacity>
          </View>
        </Modalext>

      </TouchableOpacity>
    );
  }
}

const style = StyleSheet.create({
  modal: {
    width: width - 34,
    height: 150,
    backgroundColor: '#fff',
    borderRadius: 6,
  },
  container: {
    flex: 1,
    backgroundColor: '#fff',
    paddingTop: Platform.OS === 'ios' ? 20 : 0,
  },
  wrapper: {
    backgroundColor: '#F5F5F5',
    flex: 1,
    justifyContent: 'space-between',
  },
  bg: {
    backgroundColor: '#fff',
  },
  headImg: {
    justifyContent: 'center',
    alignItems: 'center',
  },
  headPic: {
    height: PxToDp(73),
    width: PxToDp(73),
    marginRight: PxToDp(10),
  },
  infoContainer: {
    alignItems: 'flex-end',
    marginTop: PxToDp(30),
    borderTopWidth: onePR,
    borderTopColor: '#ececec',
  },
  infoList: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    height: PxToDp(56),
    width: '100%',
    paddingLeft: PxToDp(20),
    paddingRight: PxToDp(20),
    borderBottomWidth: onePR,
    borderBottomColor: '#ececec',
  },
  infoListImg: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    height: PxToDp(100),
    width: '100%',
    paddingLeft: PxToDp(20),
    paddingRight: PxToDp(20),
    borderBottomWidth: onePR,
    borderBottomColor: '#ececec',
  },
  listLeft: {
    fontSize: PxToDp(17),
    fontWeight: 'bold',
    color: '#374152',
  },
  listRight: {
    flexDirection: 'row',
  },
  rightInfo: {
    maxWidth: PxToDp(170),
    marginRight: PxToDp(20),
    fontSize: PxToDp(14),
    color: '#bbbec7',
  },
  next: {
    width: PxToDp(11),
    height: PxToDp(14),
  },
  datepicker: {
    maxWidth: PxToDp(170),
    paddingLeft: PxToDp(25),
  },
  dateNext: {
    marginTop: PxToDp(10),
  },
});
